package impl;

import anaydis.sort.SorterType;

import java.util.Comparator;
import java.util.List;

public class QuickSorter extends AbstractSorter {
    public QuickSorter() {
        super(SorterType.QUICK);
    }

    public QuickSorter(SorterType sorterType) {
        super(sorterType);
    }

    public <T> void sort(Comparator<T> comparator, List<T> list) {

        miniSort(comparator, list, 0, list.size() - 1);
    }

    protected <T> void miniSort(Comparator<T> comparator, List<T> list, int inicio, int fin) {
        miniSort(comparator, list, inicio, fin, 0);

    }

    protected <T> void miniSort(Comparator<T> comparator, List<T> list, int inicio, int fin, int dif) {


        if (inicio >= fin) return;

        int i = inicio - 1;
        int j = fin;
        int cuanto = (j-i);
        if ((j - i) > dif) {

            while (true) {

                while (greater(comparator, list, fin, ++i)) {
                    if (i == fin) {
                        break;
                    }
                }
                while (greater(comparator, list, --j, fin)) {
                    if (j <= inicio) {
                        break;
                    }
                }
                if ((j <= i)) {
                    swap(list, i, fin);
                    break;
                } else {
                    swap(list, i, j);
                }

            }
            miniSort(comparator, list, inicio, i - 1,dif);
            miniSort(comparator, list, i + 1, fin,dif);
        } else {

            InsertionSorter insertionSorter = new InsertionSorter();

            insertionSorter.sort(comparator, list, i, j);


        }

    }
}